package io.github.talelin.latticy.utils;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.*;

import java.io.*;

public class ExcelToWordConverter {
    public static void convertExcelToWord(String excelFilePath, String wordFilePath) throws IOException {
        try (InputStream inputStream = new FileInputStream(excelFilePath);
             XSSFWorkbook workbook = new XSSFWorkbook(inputStream)) {

            XSSFSheet sheet = workbook.getSheetAt(0);
            FileOutputStream outputStream = new FileOutputStream(wordFilePath);

            XWPFDocument doc = new XWPFDocument();

            for (Row row : sheet) {
                for (Cell cell : row) {
                    String cellValue = getCellValueAsString(cell);
                    XWPFParagraph p = doc.createParagraph();
                    p.createRun().setText(cellValue);
                }
            }

            doc.write(outputStream);
            outputStream.close();
        }
    }

    private static String getCellValueAsString(Cell cell) {
        switch (cell.getCellTypeEnum()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                return String.valueOf(cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return "";
        }
    }

    public static void main(String[] args) {
        try {
            convertExcelToWord("input.xlsx", "output.docx");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}